/*
 * Licensed to Jasig under one or more contributor license
 * agreements. See the NOTICE file distributed with this work
 * for additional information regarding copyright ownership.
 * Jasig licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file
 * except in compliance with the License.  You may obtain a
 * copy of the License at the following location:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

$(document).ready(function() {
    init();

    if ($('#msg.errors').size() != 0) {
        showErr("用户名或者密码错误");
    }

    $('.form-field input').focus(function() {
        $(this).parent().addClass('focus');
        $('#password, #username').parent().removeClass('error');
        $('.gui-validate-popup').remove();
    });
    $('.form-field input').focusout(function() {
        $(this).parent().removeClass('focus');
    });
    $('#login_btn').click(function() {
        login();
    });
    $('.form-field input').bind('keypress', function(event) {
        if (event.keyCode == "13") {
            login();
        }
    });
    $('#imgCode').bind('click', function() {
        var rand = Math.random() * 10000000000;
        rand = parseInt(rand);
        $('#imgCode').attr('src', '/cgi/code.php' + '?rand=' + rand);
    });
});


// 展示错误信息
function showErr(msg, id) {
    if (id != null) {
        $('#' + id).after('<div class="gui-validate-popup error"><i class="arrow"></i>' + msg + '</div>');
        $('#' + id).parent().addClass('error');
        return;
    }
    $('#password').after('<div class="gui-validate-popup error"><i class="arrow"></i>' + msg + '</div>');
    $('#password, #username').parent().addClass('error');
};

function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}
function login(defaultLoginAgain) {
    var appkey = getParameterByName('appkey');
    $(".gui-validate-popup").remove();
    if ($('#username').val() == '') {
        showErr("用户名不能为空", "username")
        return;
    }
    $('#username').parent().removeClass('error');
    if ($('#password').val() == '') {
        showErr("密码不能为空", "password")
        return;
    }
    if ($('#code').val() == '') {
        showErr("验证码不能为空", "code")
        return;
    }

    $.ajax({
        url: "/cgi/login.php",
        type: "post",
        dataType:"json",
        data: {
            "name": $("#username").val(),
            "password": $("#password").val(),
            'code': $('#code').val(),
            'appkey' : appkey
        },
        success: function(data) {
            //{code:0,skey:"skey",user:"" }
            if (data.code == 0) {
                processRedirect(data);
            } else if(data.code == 1) {
                window.location.href = "/noAccess.html";
            }
            else  if(data.code == -5) {
                showErr("验证码错误", "code");
                var rand = Math.random() * 10000000000;
                rand = parseInt(rand);
                $('#imgCode').attr('src', '/cgi/code.php' + '?rand=' + rand);
            }else {
                showErr("用户名或者密码错误");
            }
        },
        error:function(respone){
            if(console&& console.error)
                console.error(respone.responseText);
        }
    });
}

//初始页面
function init(){
    var appkey = getParameterByName('appkey');
    $.ajax({
        url: "/cgi/login.php",
        type: "post",
        dataType:"json",
        data: {
            "user": "",
            "pwd":  "",
            'code': "",
            'appkey' : appkey
        },
        success: function(data) {
            console.log(data);
            //{code:0,skey:"skey",user:"" }
            if (data.code == 0) {
                processRedirect(data);
            } else if(data.code == 1) {
                window.location.href = "/noAccess.html";
            } else {
               // showErr("用户名或者密码错误");
            }
        },
        error:function(respone){
            if(console&& console.error)
            console.error(respone.responseText);
        }

    });
}

function  processRedirect(data){
    var appkey = getParameterByName('appkey');
    var url = getParameterByName('return');
    //没有带return,没有带appkey
    if(!url||!appkey) {
        location.href="/index.html";
        return;
    }
    var skey=data.skey;
    url=decodeURIComponent(url);
    if(url.indexOf("?")>=0)
    {
        url+="&ticket="+skey;
    }else {
        url+="?ticket="+skey;
    }
    location.href=url;
}
